<script setup lang="ts">
import { awaitTo } from '@/utils'
import UploadUtil from '@/utils/upload/upload_util'
import {
  UploadFile,
  UploadMethod,
  UploadRemoveEvent,
} from 'wot-design-uni/components/wd-upload/types'

// const props = defineProps(uploadProps)
const props = withDefaults(
  defineProps<{
    modelValue: string[]
  }>(),
  {},
)

const fileList = ref<UploadFile[]>([])
const isLoad = ref(false)
watchEffect(() => {
  if (props.modelValue?.length && !isLoad.value) {
    isLoad.value = true
    fileList.value = props.modelValue.map((url) => ({
      url,
    }))
  }
})

const customUpload: UploadMethod = async (file, formData, options) => {
  file.percent = 50
  setTimeout(() => {
    file.percent = 80
  }, 10)
  const { err, result } = await awaitTo(UploadUtil.uploadImages([file.url]))
  if (result) {
    options.onSuccess({ data: result[0], statusCode: 200 }, file, formData)
  } else {
    file.percent = 0
    options.onError({ errMsg: err.message || '上传失败' }, file, formData)
  }
}

const emit = defineEmits(['update:modelValue'])
function uploadChange(value) {
  const list = value.fileList?.map((file) => file.response)
  // const isLoading = value.fileList.some((file) => file.status === 'uploading')
  // // ?.filter((item) => item.url)
  emit('update:modelValue', list)
}

function removeUpload(val: UploadRemoveEvent) {
  fileList.value.filter((item) => item.uid !== val.file.uid)
}
</script>

<template>
  <view class="use-upload">
    <wd-upload
      v-bind="$attrs"
      :file-list="fileList"
      :upload-method="customUpload"
      @success="uploadChange"
      @remove="removeUpload"
    >
      <image class="upload-btn" src="@/static/images/comment/add-picture-icon.png"></image>
    </wd-upload>
  </view>
</template>

<style lang="scss" scoped>
.upload-btn {
  width: 188rpx;
  height: 188rpx;
  background-color: #f7f8fa;
  border-radius: 20rpx;
}
</style>
